<template>
  <div class="register-container">
    <div class="register-box">
      <!-- Logo和标题 -->
      <div class="logo-section">
        <div class="logo">
          <img src="/logo.png" alt="乐享作坊" width="80" height="80" class="register-logo">
        </div>
        <h1>注册以开始聆听</h1>
      </div>

      <form @submit.prevent="register" class="register-form">
        <!-- 第一行：用户名和电子邮件 -->
        <div class="form-row">
          <div class="form-group half-width">
            <label for="username">用户名</label>
            <input 
              type="text" 
              id="username" 
              v-model="form.username" 
              placeholder="输入您的用户名"
              required
            >
            <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
          </div>

          <div class="form-group half-width">
            <label for="email">电子邮件</label>
            <input 
              type="email" 
              id="email" 
              v-model="form.email" 
              placeholder="输入您的电子邮件"
              required
            >
            <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
          </div>
        </div>

        <!-- 第二行：密码和确认密码 -->
        <div class="form-row">
          <div class="form-group half-width">
            <label for="password">密码</label>
            <input 
              type="password" 
              id="password" 
              v-model="form.password" 
              placeholder="创建密码"
              required
            >
            <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
            <div class="field-hint">至少6个字符</div>
          </div>

          <div class="form-group half-width">
            <label for="confirmPassword">确认密码</label>
            <input 
              type="password" 
              id="confirmPassword" 
              v-model="form.confirmPassword" 
              placeholder="再次输入您的密码"
              required
            >
            <span v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</span>
          </div>
        </div>

        <!-- 条款和条件 -->
        <div class="terms-section">
          <label class="checkbox-option">
            <input type="checkbox" v-model="form.acceptTerms" required>
            <span class="checkbox-checkmark"></span>
            我同意乐享作坊<a href="#" class="terms-link">使用条款</a>。
          </label>
          
          <label class="checkbox-option">
            <input type="checkbox" v-model="form.acceptPrivacy" required>
            <span class="checkbox-checkmark"></span>
            我同意乐享作坊<a href="#" class="terms-link">隐私政策</a>。
          </label>
        </div>

        <button type="submit" class="register-btn" :disabled="!isFormValid">
          注册
        </button>
      </form>

      <div class="login-link">
        <span>已有账户？</span>
        <router-link to="/users/login" class="login-btn-link">在此登录</router-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RegisterView',
  data() {
    return {
      form: {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        acceptTerms: false,
        acceptPrivacy: false
      },
      errors: {}
    }
  },
  computed: {
    passwordChecks() {
      const password = this.form.password;
      return {
        length: password.length >= 6
      };
    },
    
    isFormValid() {
      return this.form.username && 
             this.form.email && 
             this.form.password && 
             this.form.confirmPassword &&
             this.form.acceptTerms && 
             this.form.acceptPrivacy &&
             this.passwordChecks.length &&
             this.form.password === this.form.confirmPassword;
    }
  },
  methods: {
    async register() {
      this.errors = {};
      
      // 验证表单
      if (!this.validateForm()) {
        return;
      }
      
      try {
        console.log('用户注册:', this.form);
        
        // 准备发送给后端的数据
        const registerData = {
          username: this.form.username,
          email: this.form.email,
          password: this.form.password,
          acceptTerms: this.form.acceptTerms,
          acceptPrivacy: this.form.acceptPrivacy
        };
        
        // 调用后端API进行注册
        const response = await this.$http.post('/api/users/register', registerData);
        
        if (response.success) {
          // 注册成功后自动登录
          await this.autoLogin();
        } else {
          this.$root.showToast(response.message || '注册失败', 'error');
        }
      } catch (error) {
        console.error('注册失败:', error);
        const errorMessage = error.response?.data?.message || '注册失败，请稍后重试';
        this.$root.showToast(errorMessage, 'error');
      }
    },
    
    async autoLogin() {
      try {
        // 使用注册时的邮箱和密码自动登录
        const loginData = {
          emailOrUsername: this.form.email,
          password: this.form.password,
          rememberMe: false
        };
        
                  const loginResponse = await this.$http.post('/api/users/login', loginData);
        
        if (loginResponse.success) {
          // 保存token和用户信息（与登录页面保持一致）- 使用新的独立key
          localStorage.setItem('userToken', loginResponse.token);
          localStorage.setItem('userId', loginResponse.user.userId);
          localStorage.setItem('username', loginResponse.user.username);
          localStorage.setItem('userEmail', loginResponse.user.email);
          
          // 计算token过期时间
          const expiryTime = Date.now() + (24 * 60 * 60 * 1000); // 24小时
          localStorage.setItem('userTokenExpiry', expiryTime.toString());
          
          // 保存用户信息
          if (loginResponse.user) {
            localStorage.setItem('userInfo', JSON.stringify(loginResponse.user));
          }
          
          // 通知App.vue刷新登录状态
          if (this.$root.refreshLoginStatus) {
            this.$root.refreshLoginStatus();
          }
          
          // 显示统一的成功消息（注册+登录成功）
          this.$root.showToast('注册成功！欢迎来到乐享作坊！', 'success');
          
          // 跳转到首页
          this.$router.push('/');
        } else {
          // 自动登录失败，跳转到登录页面
          this.$root.showToast('注册成功！请手动登录。', 'warning');
          this.$router.push('/users/login');
        }
      } catch (error) {
        console.error('自动登录失败:', error);
        // 自动登录失败，跳转到登录页面
        this.$root.showToast('注册成功！请手动登录。', 'warning');
        this.$router.push('/users/login');
      }
    },
    
    validateForm() {
      let isValid = true;
      
      // 用户名验证
      if (!this.form.username) {
        this.errors.username = '请输入用户名';
        isValid = false;
      } else if (this.form.username.length < 3 || this.form.username.length > 20) {
        this.errors.username = '用户名长度必须在3-20个字符之间';
        isValid = false;
      } else if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(this.form.username)) {
        this.errors.username = '用户名只能包含字母、数字、下划线和中文字符';
        isValid = false;
      }
      
      // 邮箱验证
      if (!this.form.email) {
        this.errors.email = '请输入电子邮件';
        isValid = false;
      } else if (!this.isValidEmail(this.form.email)) {
        this.errors.email = '请输入有效的电子邮件地址';
        isValid = false;
      }
      
      // 密码验证
      if (!this.passwordChecks.length) {
        this.errors.password = '密码至少需要6个字符';
        isValid = false;
      }
      
      // 确认密码验证
      if (this.form.password !== this.form.confirmPassword) {
        this.errors.confirmPassword = '密码不匹配';
        isValid = false;
      }
      
      return isValid;
    },
    
    isValidEmail(email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return emailRegex.test(email);
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: #121212;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32px;
}

.register-box {
  background: #000;
  border-radius: 8px;
  padding: 48px;
  width: 100%;
  max-width: 600px;
  box-shadow: 0 4px 60px rgba(0, 0, 0, 0.5);
}

.logo-section {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  margin-bottom: 16px;
}

.register-logo {
  border-radius: 8px;
  transition: all 0.2s ease;
}

.register-logo:hover {
  transform: scale(1.1);
}

.logo-section h1 {
  color: white;
  font-size: 32px;
  font-weight: 700;
  margin: 0;
  letter-spacing: -0.04em;
}

.register-form {
  margin-bottom: 32px;
}

.form-row {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 24px;
}

.form-group.half-width {
  flex: 1;
  margin-bottom: 0;
}

.form-group label {
  display: block;
  color: white;
  font-size: 14px;
  font-weight: 700;
  margin-bottom: 8px;
}

.form-group input {
  width: 100%;
  height: 48px;
  background: #121212;
  border: 1px solid #727272;
  border-radius: 4px;
  color: white;
  font-size: 14px;
  padding: 0 12px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: white;
}

.form-group input::placeholder {
  color: #727272;
}

.checkbox-option {
  display: flex;
  align-items: center;
  color: white;
  font-size: 14px;
  cursor: pointer;
  user-select: none;
  margin-bottom: 12px;
}

.checkbox-option input {
  display: none;
}

.checkbox-checkmark {
  width: 16px;
  height: 16px;
  border: 1px solid #727272;
  border-radius: 2px;
  margin-right: 8px;
  position: relative;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.checkbox-option input:checked + .checkbox-checkmark {
  background: #1db954;
  border-color: #1db954;
}

.checkbox-option input:checked + .checkbox-checkmark::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.password-requirements {
  margin-top: 8px;
  font-size: 12px;
  color: #b3b3b3;
}

.password-requirements ul {
  margin: 4px 0;
  padding-left: 16px;
}

.password-requirements li {
  margin: 2px 0;
  transition: color 0.3s ease;
}

.password-requirements li.valid {
  color: #1db954;
}

.error-message {
  display: block;
  color: #e22134;
  font-size: 12px;
  margin-top: 4px;
}

.field-hint {
  display: block;
  color: #b3b3b3;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.4;
}

.terms-section {
  margin-bottom: 32px;
  padding: 16px 0;
  border-top: 1px solid #282828;
}

.terms-link {
  color: #1db954;
  text-decoration: none;
}

.terms-link:hover {
  text-decoration: underline;
}

.register-btn {
  width: 100%;
  height: 48px;
  background: #1db954;
  border: none;
  border-radius: 500px;
  color: black;
  font-size: 14px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.register-btn:hover:not(:disabled) {
  background: #1ed760;
  transform: scale(1.02);
}

.register-btn:disabled {
  background: #535353;
  cursor: not-allowed;
  transform: none;
}

.login-link {
  text-align: center;
}

.login-link span {
  color: #727272;
  font-size: 16px;
  margin-right: 4px;
}

.login-btn-link {
  color: white;
  font-size: 16px;
  text-decoration: underline;
  transition: color 0.3s ease;
}

.login-btn-link:hover {
  color: #1db954;
}

@media (max-width: 768px) {
  .register-container {
    padding: 16px;
  }
  
  .register-box {
    padding: 24px;
    max-width: 100%;
  }
  
  .logo-section h1 {
    font-size: 28px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-group.half-width {
    margin-bottom: 24px;
  }
}
</style> 